'use client';

import { signup } from 'src/actions/user';
import { startTransition, useActionState, useCallback } from 'react';
import Link from 'next/link';
import { Alert } from 'src/components/Alert';
import { useRouter } from 'next/navigation';
import { EnvelopeIcon, LockClosedIcon, UserIcon } from '@heroicons/react/24/outline';

export default function Signup() {
  const [state, action, pending] = useActionState(signup, undefined);

  const router = useRouter();

  const handleSubmit = useCallback(
    (event: React.FormEvent<HTMLFormElement>) => {
      event.preventDefault();
      const formData = new FormData(event.currentTarget);
      startTransition(async () => {
        await action(formData);
      });
    },
    [action]
  );

  const handleRedirect = useCallback(() => {
    router.push('/login');
  }, [router]);

  return (
    <div className="flex items-center justify-center min-h-screen bg-gradient-to-b from-gray-100 to-purple-200 dark:from-neutral-800 dark:to-purple-950 p-4">
      {state?.status === 'success' && (
        <Alert
          key={state.actionId}
          duration={2500}
          type="success"
          message="恭喜，您的账户已注册成功，请登录继续使用我们的服务。"
          onClose={handleRedirect}
        />
      )}
      {state?.status === 'error' && (
        <Alert
          key={state.actionId}
          duration={5000}
          type="error"
          message={state.errors?.message ?? '发生错误'}
        />
      )}
      <div className="w-full max-w-md p-8 space-y-8 bg-white dark:bg-neutral-950 rounded-2xl shadow-lg">
        <div className="text-center">
          <h1 className="text-3xl font-bold">注册账号</h1>
          <p className="mt-2 text-sm text-gray-600 dark:text-neutral-400">
            请填写以下信息创建“星恒云图”账户
          </p>
        </div>

        <form onSubmit={handleSubmit} className="mt-8">
          <fieldset className="fieldset text-sm">
            <label htmlFor="name" className="label">
              用户名
            </label>
            <label className="input input-lg w-full pr-0">
              <UserIcon className="size-6 opacity-75" />
              <input id="name" name="name" placeholder="输入您的用户名" autoComplete="off" />
            </label>
            {state?.errors?.form?.name && (
              <p className="mt-1 text-xs text-error">{state.errors.form.name}</p>
            )}

            <label htmlFor="email" className="label mt-4">
              电子邮箱
            </label>
            <label className="input input-lg w-full pr-0">
              <EnvelopeIcon className="size-6 opacity-75" />
              <input
                id="email"
                name="email"
                type="email"
                autoComplete="off"
                placeholder="输入您的邮箱地址"
              />
            </label>
            {state?.errors?.form?.email && (
              <p className="mt-1 text-xs text-error">{state.errors.form.email}</p>
            )}

            <label htmlFor="password" className="label mt-4">
              密码
            </label>
            <label className="input input-lg w-full pr-0">
              <LockClosedIcon className="size-6 opacity-75" />
              <input
                id="password"
                name="password"
                type="password"
                placeholder="设置您的密码"
                autoComplete="new-password"
              />
            </label>
            {state?.errors?.form?.password && (
              <div className="mt-1 text-xs text-error">
                <p>密码必须：</p>
                <ul className="pl-5 mt-1 list-disc">
                  {state.errors.form.password.map((error) => (
                    <li key={error}>{error}</li>
                  ))}
                </ul>
              </div>
            )}

            <button
              disabled={pending}
              type="submit"
              className="w-full mt-5 py-3 px-4 text-lg bg-gradient-to-r from-purple-500 to-purple-600 text-white font-medium rounded-lg transition-all duration-200 hover:from-purple-600 hover:to-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-opacity-50 disabled:opacity-70"
            >
              {pending ? '注册中...' : '立即注册'}
            </button>
          </fieldset>
        </form>

        <div className="text-center text-sm text-gray-600 dark:text-neutral-400">
          <p>
            已有账号？
            <Link href="/login" className="text-blue-600 hover:text-blue-800 font-medium">
              登录
            </Link>
          </p>
        </div>
      </div>
    </div>
  );
}
